package injection;

import domain.User;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * Autowired 依赖字段注入
 * @author jackcfan
 * @date 2021/9/16
 */
public class AnnotationFieldInjectionTest {
    // Autowired 会忽略掉静态 static 字段
    @Autowired
    /*static*/ UserHolder userHolder;
    @Resource
    User user;

    @Test
    public void test(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration class 配置类
        applicationContext.register(this.getClass());

        // 启动 Spring 上下文
        applicationContext.refresh();

        AnnotationFieldInjectionTest annotation = applicationContext.getBean(this.getClass());
        System.out.println("userHolder>"+annotation.userHolder);
        System.out.println("user>"+annotation.user);

        applicationContext.close();
    }

    @Bean
    public User user(){
        User user = new User();
        user.setName("AnnotationFieldInjectionTest");
        user.setId(1L);
        return user;
    }

    @Bean
    public UserHolder userHolder(User user){
        return new UserHolder(user);
    }
}
